package com.panda.QQserver.service;

import com.panda.qqcommon.Message;
import com.panda.qqcommon.MessageType;
import com.panda.qqcommon.User;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ConcurrentHashMap;

public class QQServer {
    /**
     * 这里是服务器，监听9999端口
     */

    private ServerSocket serverSocket=null;

    //用于存放已经注册的用户
    private static ConcurrentHashMap<String,User> validUsers=new ConcurrentHashMap<>();

    static {
        validUsers.put("100",new User("100","100"));
        validUsers.put("200",new User("200","200"));
        validUsers.put("300",new User("300","300"));
        validUsers.put("400",new User("400","400"));
        validUsers.put("500",new User("500","500"));
    }

    public boolean isValidUser(String userId,String password){
        if(validUsers.containsKey(userId)){
            if(validUsers.get(userId).getPassword().equals(password)){
                return true;
            }
        }
        return false;
    }

    public  QQServer() throws IOException, ClassNotFoundException {
        serverSocket=new ServerSocket(9999);

        while(true){
            System.out.println("\n服务端在9999监听中。。。");
            //每次接受一个客户端，就会产生一个socket
            Socket socket=serverSocket.accept();
            ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
            User user = (User)objectInputStream.readObject();
            System.out.println("have receive the user:"+user);

            Message message = new Message();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());



            //验证是否有这个用户
            if(isValidUser(user.getUserId(), user.getPassword())){  //后续补充
                System.out.println("验证成功");
                message.setMessageType(MessageType.MESSAGE_LOGIN_SUCCEED);
                objectOutputStream.writeObject(message);
                System.out.println("have output the message:"+message);
                //创建一个线程，和客户端持续联系
                ServerConnectClientThread serverConnectClientThread = new ServerConnectClientThread(socket, user.getUserId());
                //启动该线程，和用户持续交互
                serverConnectClientThread.start();
                System.out.println("客户端的一个线程已经创建");
                //将该线程放入集合中管理
                ManageClientThreads.add(user.getUserId(),serverConnectClientThread);


            }else {
                System.out.println("验证失败");
                message.setMessageType(MessageType.MESSAGE_LOGIN_FAIL);
                objectOutputStream.writeObject(message);
            }



        }
    }

}
